var MAX_VALUE_SHOW_SIZE = 40,
      MAX_URL_SHOW_SIZE = 30;
      

function getElementsByClassName(strClassName, obj) {
    var classElements = arguments[2] || [],
	regExp = new RegExp("\\b" + strClassName + "\\b", "g");

    if (regExp.test(obj.className)) {
        classElements.push(obj);
    }
    for (var i = 0, max = obj.childNodes.length; i < max; i++)
        getElementsByClassName(strClassName, obj.childNodes[i], classElements);
    
    return classElements;
}


function substituteContentByClass(className,originalContent,newContent){
    var classElements = getElementsByClassName(className, document.body);
    for (var i = 0, max = classElements.length; i < max; i++) {
      if(classElements[i].textContent==originalContent) {
	 classElements[i].innerHTML=newContent;
      }
    }
}

//accordion - start
var s = 7000;
var t = 0;
   
function dsp(d, v) {
    if (!v) {
	return d.style.display;
    } else {
	d.style.display = v;
    }
}

// set or get the height of a div.

function sh(d, v) {
    var viz, o, r, factor_r;
    // if you are getting the height then display must be block to return the absolute height
    if (!v) {
	if (dsp(d) != 'none' && dsp(d) != '') {
	    return d.offsetHeight;
	}
	viz = d.style.visibility;
	d.style.visibility = 'hidden';
	o = dsp(d);
	dsp(d, 'block');
	r = parseInt(d.offsetHeight);
	dsp(d, o);
	d.style.visibility = viz;
	factor_r = 1.25;
	if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) 
	    factor_r = 1.22;
	//return r*factor_r;
	return definedSize;    
    } else {
	d.style.height = v;
	d.style.overflowY = "visible";
    }
}

//Collapse Timer is triggered as a setInterval to reduce the height of the div exponentially.

function ct(d) {
   d = document.getElementById(d);
   sh(d, 0);
   dsp(d, 'none');
   clearInterval(d.t);
}

//Expand Timer is triggered as a setInterval to increase the height of the div exponentially.

function et(d) {
    var v;
    d = document.getElementById(d);
    if (sh(d) < d.maxh) {
	v = Math.round((d.maxh - sh(d)) / d.s);
	v = (v < 1) ? 1 : v;
	v = sh(d) + v;
	sh(d, v + 'px');
	d.style.opacity = (v / d.maxh);
	d.style.filter= 'alpha(opacity='+(v*100 / d.maxh) + ');';
    } else {
	sh(d, d.maxh);
	clearInterval(d.t);
    }
}

// Collapse Initializer

function cl(d) {
    if (dsp(d) == 'block') {
	clearInterval(d.t);
	d.t = setInterval('ct("' + d.id + '")', t);
    }
}

//Expand Initializer

function ex(d) {
    if (dsp(d) == 'none') {
	dsp(d, 'block');
	d.style.height='0px';
	clearInterval(d.t);
	d.t = setInterval('et("' + d.id + '")', t);
    }
}

// Removes Classname from the given div.

function cc(n, v){
    s = n.className.split(/\s+/);
    for (var p = 0, max = s.length;p < max;p++) {
	if (s[p] == v + n.tc) {
	    s.splice(p, 1);
	    n.className=s.join(' ');
	    break;
	}
    }
}

//Accordian Initializer

function Accordian(d, s, tc) {
    // get all the elements that have id as content
    var l = document.getElementById(d).getElementsByTagName('div'),
	c = [],
	sel = null,
	h, cn, n;
    for (var i = 0, max = l.length;i < max;i++) {
	var h = l[i].id;
	if (h.substr(h.indexOf('-') + 1,h.length) == 'content') {c.push(h);}
    }
    //then search through headers
    for (var i = 0, max = l.length;i < max;i++) {
	h = l[i].id;
	if (h.substr(h.indexOf('-') + 1, h.length) == 'header') {
	    d=document.getElementById(h.substr(0, h.indexOf('-'))+'-content');
	    d.style.display = 'none';
	    d.style.overflow = 'hidden';
	    d.maxh = sh(d);
	    d.s = (s==undefined)? 7 : s;
	    h = document.getElementById(h);
	    h.tc = tc;
	    h.c = c;
	    // set the onclick function for each header.
	    h.onclick = function() {
		for (var i = 0, max = c.length;i < max;i++) {
		    cn = this.c[i];
		    n = cn.substr(0,cn.indexOf('-'));
		    if ((n + '-header') == this.id) {
			ex(document.getElementById(n + '-content'));
			n = document.getElementById(n + '-header');
			cc(n,'__');
			n.className=n.className+' '+n.tc;
		    } else {
			cl(document.getElementById(n + '-content'));
			cc(document.getElementById(n + '-header'),'');
		    }
		}
	    }
	    if (sel == undefined){ sel=h;}
	}
    }
    if (sel != undefined){sel.onclick();}
}
//accordion - end

function changeHeader() {
      var headerElements = getElementsByClassName('form-manager', document.body),
            headerLabel = "Customer Status Report";
      if (headerElements.length == 0) {
         return;
      }
      if (formMode == "edit")
         headerLabel = "Edit " + headerLabel;
      else
         document.getElementById(varFormId + "-caption-label").innerHTML = "&nbsp;";
      document.getElementById(varId+"-dialogTitle").innerHTML = "";
      headerElements[0].innerHTML = "<h1>" + headerLabel + "</h1>";
}
   
function getCreatorName(creatorJson) {
      if (creatorJson.lastName != null && creatorJson.lastName != "")
         return creatorJson.lastName + ", " + creatorJson.firstName;
      else if (creatorJson.firstName != null && creatorJson.firstName != "")
         return creatorJson.firstName;
      else
         return "(" + creatorJson.userName + ")";
}

function revertVersion(versionLabel) {
      if (window.confirm("Are you sure you want to revert to the version " + versionLabel + "?")) {
        Alfresco.util.Ajax.request({
              url: Alfresco.constants.PROXY_URI + "csr/revert?nodeRef=" + nodeRef + "&version=" + versionLabel,
              successCallback:
              {
                 fn: function(p_obj) {
                    window.location.reload();
                 },
                 scope: this
              },
              failureMessage: "error reverting version"
          });
      }
}

function getVersionHtmlInfo(jsonObj,includeRevert) {
      var htmlInfo = "Version <b>" + jsonObj.label + "</b>";
      if (includeRevert)
         htmlInfo += " <a href='#' onclick='revertVersion(\""+
            jsonObj.label + "\")'><img title='revert' src='/share/components/images/revert-16.png' border='0'/></a>";
      if (jsonObj.description != null && jsonObj.description != "")
         htmlInfo += "<br/>" + jsonObj.description;
      return htmlInfo + "<br/>Created at " + jsonObj.createdDate +
         " by " + getCreatorName(jsonObj.creator) + "<br/><br/>";
}

function fulfillHtmlVersion(jsonObjList) {
      var innerhtml = "";
      for(var i = 0, max = jsonObjList.length;i < max;i++) {
        innerhtml += getVersionHtmlInfo(jsonObjList[i], i != 0);
      }
      document.getElementById("version-control-layer").innerHTML = innerhtml;
}

function checkAndFulfillVersionControl() {
      if (nodeRef == "dlswr:swReport")
         return;
      fulfillVersionControl();
}

function fulfillVersionControl() {
      var versionUrl = Alfresco.constants.PROXY_URI + "api/version?nodeRef=" + nodeRef;
      Alfresco.util.Ajax.request({
         url: versionUrl,
         successCallback:
         {
            fn: function(p_obj) {
               fulfillHtmlVersion(p_obj.json);
            },
            scope: this
         },
         failureMessage: "error loading versions"
      });
   
}

function showFullRTFValue(divElementId) {
      Alfresco.util.PopupManager.displayPrompt({
            title: document.getElementById(divElementId).parentNode.firstChild.nextSibling.textContent,
            text: "-"
      });
      setTimeout("formatFullRTFValue('" + divElementId + "')", 15);
}

function formatFullRTFValue(divElementId) {
      var promptContent = getElementsByClassName( "bd", document.getElementById("prompt" ))[0];
      promptContent.style.textAlign = "left";
      promptContent.innerHTML = document.getElementById(divElementId).innerHTML;
      document.getElementById("prompt").parentNode.style.width = "90%";
      document.getElementById("prompt").parentNode.style.position = "absolute";
      document.getElementById("prompt").parentNode.style.top = "50px";
      document.getElementById("prompt").parentNode.style.left = "50px";
      promptContent.style.height = "515px";
      promptContent.style.overflowY = "scroll";
      promptContent.style.overflowX = "hidden";
      return false;
}

function stripHTMLTags() {
      var arrayClassElements = getElementsByClassName( 'viewmode-value', document.body );
      for ( var i = 0, max = arrayClassElements.length; i < max; i++ ) {
            arrayClassElements[i].innerHTML = arrayClassElements[i].textContent;
            if (arrayClassElements[i].textContent.length > MAX_VALUE_SHOW_SIZE) {
                  divElement = document.createElement('div');
                  divElement.style.width = "350px";
                  divElement.style.height = "35px";
                  divElement.style.border = "1px solid gray";
                  divElement.style.overflow = "hidden";
                  divElement.style.cursor = "pointer";
                  divElement.id = "RTF-" + Math.floor(Math.random() * 10001);
                  divElement.setAttribute("onclick", "showFullRTFValue('" + divElement.id + "');");
                  arrayClassElements[i].parentNode.appendChild(divElement);
                  divElement.appendChild(arrayClassElements[i]);
                  var divElementTooltip = new YAHOO.widget.Tooltip("tooltip-"+divElement.id, { 
                        context: divElement.id, 
                        text: "Click to show all content",
                        showDelay: 500
                 });
            }
      }
}

function reduceUrlFields() {
      var urlHrefElements = getElementsByClassName( 'dummyurlclass', document.body ),
            CUT_LABEL = "...";
      for ( var i = 0, max = urlHrefElements.length; i < max; i++ ) {
            if (urlHrefElements[i].textContent.length > MAX_URL_SHOW_SIZE) {
                  urlHrefElements[i].textContent = urlHrefElements[i].textContent.substring(0, MAX_URL_SHOW_SIZE - CUT_LABEL.length) + CUT_LABEL;
            }
      }
}

function substituteNoneByClass(className) {
   substituteContentByClass(className,"(None)", "-");
}

function substituteNone() {
   substituteNoneByClass('viewmode-value');
}

function likeUnlikeCSR(){
	var likeLink=Dom.get("likeLink");
	if(likeLink.title=="Unlike"){
		unlikeCSR();
	}else{
		likeCSR();
	}
}

function unlikeCSR(){
	var ratingUrl = Alfresco.constants.PROXY_URI + "api/node/" + nodeRef.replace("://","/")+"/ratings/likesRatingScheme";
	Alfresco.util.Ajax.request({
         url: ratingUrl,
	method: Alfresco.util.Ajax.DELETE,
         successCallback:
         {
            fn: function(p_obj) {
               var likesCount= Dom.get("likesCount");
		likesCount.innerHTML=parseInt(likesCount.innerHTML)-1;
		deactivateLikesIcon();
            },
            scope: this
         },
         failureMessage: "error unliking CSR"
      });
}

function likeCSR(){
	var ratingUrl = Alfresco.constants.PROXY_URI + "api/node/" + nodeRef.replace("://","/")+"/ratings";
	Alfresco.util.Ajax.request({
         url: ratingUrl,
	requestContentType: Alfresco.util.Ajax.JSON,
	method: Alfresco.util.Ajax.POST,
	dataObj:
	{
			rating: 1,
			ratingScheme: "likesRatingScheme"
	},
         successCallback:
         {
            fn: function(p_obj) {
               var likesCount= Dom.get("likesCount");
		likesCount.innerHTML=parseInt(likesCount.innerHTML)+1;
		activateLikesIcon();
            },
            scope: this
         },
         failureMessage: "error liking CSR"
      });
}

function deactivateLikesIcon(){
	var likesIcon=Dom.get("likesIcon");
	likesIcon.src="/share/components/images/like-16.png";
	var likePhrase=Dom.get("likeOpPhrase");
	likePhrase.innerHTML="Like";
	var likeLink=Dom.get("likeLink");
	likeLink.title="Like this CSR";
}

function activateLikesIcon(){
	var likesIcon=Dom.get("likesIcon");
	likesIcon.src="/share/components/images/liked-16.png";
	var likePhrase=Dom.get("likeOpPhrase");
	likePhrase.innerHTML="";
	var likeLink=Dom.get("likeLink");
	likeLink.title="Unlike";
}

function fulfillRatingInfo(jsonObj) {
	var likesCount= Dom.get("likesCount");
	var ratingResult=jsonObj.data.nodeStatistics.likesRatingScheme.ratingsTotal;
	likesCount.innerHTML=ratingResult==-1?0:ratingResult;
	if(jsonObj.data.ratings.likesRatingScheme!=null){
		activateLikesIcon();
	}
}

function updateRating() {
	var ratingUrl = Alfresco.constants.PROXY_URI + "api/node/" + nodeRef.replace("://","/")+"/ratings";
	 Alfresco.util.Ajax.request({
         url: ratingUrl,
         successCallback:
         {
            fn: function(p_obj) {
               fulfillRatingInfo(p_obj.json);
            },
            scope: this
         },
         failureMessage: "error loading ratings"
      });
}
   
function initAcc() {
      if(formMode == "view") {
            stripHTMLTags();
            substituteNone();
            reduceUrlFields();
      }
      if (formMode == "create") {
            try{
                  document.getElementById("${id}-dialog_c").style.width = "90%";
                  document.getElementById("${id}-dialog").style.width = "100%";
                  document.getElementById("${id}-dialog").style.height = "100%";
            } catch (e) {}
      } else {
            checkAndFulfillVersionControl();
      }
      
      changeHeader();
      
      new Accordian('basic-accordian', 5, 'header_highlight');

	if(formMode=="view")
	      updateRating();
      
      return false;
}

